package com.gthncz.locks;

import java.util.Random;

/**
 * 动态指数退避的 TTASLock.
 */
public class BackoffTTASLock extends TTASLock {

    private final long BACKOFF_MIN = 20;
    private final long BACKOFF_MAX = 20000;

    private ThreadLocal<Long> delay = new ThreadLocal<>();
    private Random random = new Random();

    @Override
    public void lock() {
        delay.set(BACKOFF_MIN);
        while(true){
            while (state.get());
            if (state.getAndSet(true) == false){
                break;
            }
            try {
                Thread.sleep(random.nextLong() % delay.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (delay.get() < BACKOFF_MAX){
                delay.set(2 * delay.get());
            }
        }
    }

    @Override
    public void unlock() {
        super.unlock();
    }
}
